import * as echarts from '../../plugin/ec-canvas/echarts';
// pages/login/login.js
//获取应用实例
const app = getApp()
const util = require('../../../utils/util.js')
var chart1 = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loadding : 0,
    curTime:'xxxx-xx-xx xx:xx:xx',
    judes : 0 ,
    ec1:{
      onInit: function (canvas, width, height) {
        chart1 = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart1);
        return chart1;
      },
      // lazyLoad: true 
    },
  },
  onLoad: function(options) {
    let that = this 
    setTimeout(this.getData,1000);
    // this.oneComponent = this.selectComponent('#mychart-dom-bar')
    // that.getData() ;
  },
  // onReady: function(){
  //   this.oneComponent = this.selectComponent('#mychart-dom-bar');  
  // },
  // onInit: function (xdata, ydata) {
  //   this.oneComponent.init((canvas, width, height) => {
  //     const chart1 = echarts.init(canvas, null, {
  //         width: width,
  //         height: height
  //     });
  //     canvas.setChart(chart1);
  //     this.setOptions(chart1, xdata, ydata)
  //     this.chart1 = chart1;
  //     return chart1;
  //   });
  // },
  getData: function(e){
    let questionList = []
    let allUserNameAndAttendNumberList = []
    let dateTime=util.formatTime2(new Date());
  //  chart1.showLoading()
    wx.request({
      url: app.backstageUrl + '/WeChat/Statistics/getDutyWeekInfo',
      method: 'GET',
      data: {
        departmentId : parseInt(app.globalData.departmentId) ,
        dateTime : dateTime
      },
      dataType: 'json',
      success: (res) => {
        let that = this 
     //   that.onInit(res.data.totalDutyWeekNum,res.data.realDutyWeekNum)
        console.log("data",res.data)
        let photoes = []
        let deductionRankList = []
        let judes = 0
        res.data.questionList.forEach((item,index) =>{
          if(item.photo == "") {
            questionList.push({
              realname : item.realname ,
              dateTime : item.createTime ,
              address : item.address ,
              content: item.content ,
              deduction : item.deduction ,
              item : item.item ,
              category : item.category ,
              photo : '',
              video: item.video,
              videoSrc: app.imageUrl + item.video
            }) 
          }else if(item.photo.split(",")){
            for (let i = 0; i < item.photo.split(',').length; i++) {
              photoes.push(item.photo.split(',')[i])
            }
            questionList.push({
              realname : item.realname ,
              dateTime : item.createTime ,
              address : item.address ,
              content: item.content ,
              deduction : item.deduction ,
              item : item.item ,
              category : item.category ,
              photo : item.photo.split(',')[0] ,
              photoLength: item.photo.split(',').length,
              video: item.video,
              videoSrc: app.imageUrl + item.video
            }) 
          }else{
            photoes.push(item.photo)
            questionList.push({
              realname : item.realname ,
              dateTime : item.createTime ,
              address : item.address ,
              content: item.content ,
              deduction : item.deduction ,
              item : item.item ,
              category : item.category ,
              photo : item.photo,
              photoLength: 1,
              video: item.video,
              videoSrc: app.imageUrl + item.video
            })
          } 
        })
        res.data.allUserNameAndAttendNumber.forEach((item,index) =>{
          allUserNameAndAttendNumberList.push({
            userId : item.userId ,
            realname : item.realname ,
            times: item.attendnumber ,
            curTime : dateTime
          }) 
        })
        deductionRankList = res.data.deductionRankList
        deductionRankList.forEach((item,index)=>{
          try {
            if(item.deductionNum != 0){
              judes = 1 ;
              throw Error();
            }
          } catch (e) {
          }
        }) 
        let dateTime2=util.formatTime2(new Date());
        this.setData({
          loadding : 1 ,
          judes : judes ,
          schoolName: app.globalData.department,
          charger: app.globalData.realname ,
          curTime: dateTime2 ,
          questionList : questionList ,
          photoes : photoes ,
          allUserNameAndAttendNumberList : allUserNameAndAttendNumberList ,
          deductionRankList : deductionRankList
        })
        let totalDutyWeekNum = res.data.totalDutyWeekNum
        let realDutyWeekNum = res.data.realDutyWeekNum
     //  今日总值周次数/已完成值周次数
        chart1.setOption({
          tooltip: {
            show:false,
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
          },
          color:["#DEB0A7"],
          series: [
            {
                name:'访问来源',
                type:'pie',
                radius: ['50%', '60%'],
                center: ['50%', '50%'],
                avoidLabelOverlap: false,
                hoveranination:false,
                silent:true,
                label: {
                    normal: {
                        show: true,
                        position: 'center',
                        formatter:function (argument) {
                            var html;
                            html='已完成\r\n\r\n'+realDutyWeekNum;
                            return html;
                        },
                        textStyle:{
                            fontSize: 22,
                            color:'#272524'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data:[
                    {value:0, name:''}
                ]
            }
          ]
        })
     //   chart1.hideLoading()
      },
    })
  },

  previewImage: function (e) {
      console.log(e)
      wx.previewImage({
        current: e.target.dataset.src, // 当前显示图片的http链接
        urls: this.data.photoes // 需要预览的图片http链接列表
      })
  },
  //日期选择器
  bindDateChange:function(e){
    this.setData({
      date : e.detail.value
    })
  },
   //从搜索按钮 点击搜索
   searchButton: function(e) {
    let inputContent = app.trim(e.detail.value.input)
    this.searchItem(inputContent)
  },
  searchItem: function(inputContent) {
    if (!inputContent) {
      wx.showToast({
        title: '请输入关键字！',
        icon: 'none',
        duration: 800,
        mask: true
      })
      // this.setData({
      //   loadding: 1
      // })
    }else{
      console.log("inputContent",inputContent)     
      if (!util.strDateTime(inputContent)) {
        wx.showToast({
           title: '未搜索到符合条件的记录！',
           icon: 'none',
           duration: 800,
           mask: true
         })
      }else{
        this.setData({
          loadding: 0
        })
      //  chart1.showLoading();
        wx.request({
          url: app.backstageUrl + '/WeChat/Statistics/getDutyWeekInfo',
          method: 'GET',
          data: {
            departmentId : parseInt(app.globalData.departmentId) ,
            dateTime : inputContent
          },
          success: res => {
            let photoes = []
            let questionList = []
            let allUserNameAndAttendNumberList = []
            let deductionRankList = []
            let judes = 0
            let that = this 
         //   that.onInit(res.data.totalDutyWeekNum,res.data.realDutyWeekNum)
            res.data.questionList.forEach((item,index) =>{
              if(item.photo == "") {
                questionList.push({
                realname : item.realname ,
                dateTime : item.createTime ,
                address : item.address ,
                content: item.content ,
                deduction : item.deduction ,
                item : item.item ,
                category : item.category ,
                photo : '',
                video: item.video,
                videoSrc: app.imageUrl + item.video
              }) 
            }else if(item.photo.split(",")){
              for (let i = 0; i < item.photo.split(',').length; i++) {
                photoes.push(item.photo.split(',')[i])
              }
              questionList.push({
                realname : item.realname ,
                dateTime : item.createTime ,
                address : item.address ,
                content: item.content ,
                deduction : item.deduction ,
                item : item.item ,
                category : item.category ,
                photo : item.photo.split(',')[0],
                photoLength: item.photo.split(',').length,
                video: item.video,
                videoSrc: app.imageUrl + item.video
              }) 
            }else{
              photoes.push(item.photo)
              questionList.push({
                realname : item.realname ,
                dateTime : item.createTime ,
                address : item.address ,
                content: item.content ,
                deduction : item.deduction ,
                item : item.item ,
                category : item.category ,
                photo : item.photo ,
                photoLength: 1,
                video: item.video,
                videoSrc: app.imageUrl + item.video
              })
            } 
          })
          res.data.allUserNameAndAttendNumber.forEach((item,index) =>{
            allUserNameAndAttendNumberList.push({
              userId : item.userId ,
              realname : item.realname ,
              times: item.attendnumber ,
              curTime : inputContent
            }) 
          })
          deductionRankList = res.data.deductionRankList
          deductionRankList.forEach((item,index)=>{
            try {
              if(item.deductionNum != 0){
                judes = 1 ;
                throw Error();
              }
            } catch (e) {
            }
          })
          wx.showToast({
            title: '搜索成功！',
            icon: 'none',
            duration: 1000
          })
          this.setData({
            loadding: 1 ,
            judes : judes ,
            schoolName: app.globalData.department,
            charger: app.globalData.realname ,
            curTime: inputContent ,
            questionList : questionList ,
            photoes : photoes ,
            allUserNameAndAttendNumberList : allUserNameAndAttendNumberList ,
            deductionRankList : deductionRankList
          })
          let totalDutyWeekNum = res.data.totalDutyWeekNum
          let realDutyWeekNum = res.data.realDutyWeekNum
          chart1.setOption({
            tooltip: {
              show:false,
              trigger: 'item',
              formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            color:["#DEB0A7"],
            series: [
              {
                  name:'访问来源',
                  type:'pie',
                  radius: ['50%', '60%'],
                  center: ['50%', '50%'],
                  avoidLabelOverlap: false,
                  hoveranination:false,
                  silent:true,
                  label: {
                      normal: {
                          show: true,
                          position: 'center',
                          formatter:function (argument) {
                              var html;
                              html='已完成\r\n\r\n'+realDutyWeekNum;
                              return html;
                          },
                          textStyle:{
                              fontSize: 22,
                              color:'#272524'
                          }
                      }
                  },
                  labelLine: {
                      normal: {
                          show: false
                      }
                  },
                  data:[
                      {value:0, name:''}
                  ]
              }
            ]
           })
     //     chart1.hideLoading();
          }
          
        })
      }
    } 
  },

  //饼状图样式
  setOptions : function(chart1,totalDutyWeekNum,realDutyWeekNum){
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      title: {
        left: 'center',
        top:'10px'
      },
      animation: false,
      series: [
         {
            type: 'pie',
            radius: ['%', '42%'],
            center: ['48%', '50%'] ,
            label: {
                formatter: '{b|{b}：}{c|{c}}',
                backgroundColor: '#eee',
                borderColor: '#aaa',
                rich: {
                    b: {
                        fontSize: 16,
                    },
                    c:{
                        fontSize: 18,
                    },
                    per: {
                        fontSize: 16,
                        color: '#eee',
                        backgroundColor: '#334455',
                        padding: [4, 2],
                        borderRadius: 2
                    }
                }
            },
            data: [
              {value: totalDutyWeekNum , name: '总次数'},
              {value: realDutyWeekNum , name: '已完成'},
          ]
         }
      ]
    }
    chart1.setOption(option)
  },

  toDutyWeekDetail :function(e){
    console.log("e=============================", e)
    wx.navigateTo({
      url: '../dutyweekDetail/dutyweekDetail?userId='+e.currentTarget.dataset.item.userId+'&curTime='+e.currentTarget.dataset.item.curTime+'&realname='
      +e.currentTarget.dataset.item.realname,
    })
  },
  toDeductionDetail: function(e){
    var curTime = e.currentTarget.dataset.item.createTime.split(" ")[0] ;
    console.log("curTime",curTime)
    wx.navigateTo({
      url: '../dutyweekDeductionDetail/dutyweekDeductionDetail?checkpointId='+e.currentTarget.dataset.item.checkpointId+'&curTime='+curTime
    })
  },

  clearSelect:function(){
    wx.showToast({
      title: '返回成功',
      icon: 'none',
      duration: 800,
      mask: true
    })
    this.onLoad() ;
  },

})

